package com.example.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.util.ZipUtil;

@RestController
@RequestMapping("/test")
public class FileImportController {
	
	@PostMapping("/import")
	public void importTest(@RequestParam("file") MultipartFile file ,HttpServletRequest request) {
		// 原始文件名称
		String fileName = file.getOriginalFilename();
		InputStream zipStream;
		try {
			zipStream = file.getInputStream();
			long currentTime = System.currentTimeMillis();
			File  distFile = new File("/home/uniubi/zipFile/"+currentTime, fileName);;
			FileUtils.copyInputStreamToFile(zipStream, distFile);
			System.out.println("upload complete");
			zipStream.close();
			
			// 逻辑处理
			// 解压文件			
			List<File> upzipFileList = ZipUtil.upzipFile(distFile, "/home/uniubi/unZipFile/" + currentTime);		

			System.out.println(distFile.getAbsolutePath());
			boolean b = distFile.delete();	
			System.out.println(b);
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					upzipFileList.forEach(tempFile->{
						boolean a = tempFile.delete();
						System.out.println(a);
					});
					
				}
			}).start();
			
			
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	@DeleteMapping("/delete/folder")
	public void deleteFolder() {
		File fileZipDir = new File("/home/uniubi/zipFile");
		File fileUnZipDir = new File("/home/uniubi/unZipFile");

		deleteFile(fileZipDir);
		deleteFile(fileUnZipDir);
				
	}
	
	private void deleteFile(File file) {
		// 是文件直接删除
		if(file.exists()) {
			if(file.isFile()) {
				file.delete();
				System.out.println("删除文件："+ file.getAbsolutePath());
			 
			}else {
				// 如果是空文件夹，直接删除文件夹
				if(file.listFiles().length ==0 ) {
					file.delete();
					System.out.println("删除文件夹："+ file.getAbsolutePath());
				}else {
					// 如果不是空文件夹，先删掉里边的文件，再删除文件夹本身
					File[] fileList = file.listFiles();
					for(File innerFile  : fileList) {
						deleteFile(innerFile);
					}
					file.delete();
					System.out.println("删除文件夹：" + file.getAbsolutePath());
				}
			}
		}else {
			System.out.println("文件不存在");
		}
		
	}
}
